import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Modal, StyleSheet, Platform } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../constants/colors';

interface Props {
  label: string;
  value?: string;
  onChange: (hhmmss: string) => void;
  variant?: 'stacked' | 'card';
}

export default function TimeField({ label, value, onChange, variant = 'card' }: Props) {
  const [visible, setVisible] = useState(false);
  const [time, setTime] = useState<Date>(() => {
    if (!value) return new Date();
    const parts = value.split(':').map(Number);
    const h = parts[0] || 0;
    const m = parts[1] || 0;
    const s = parts[2] || 0;
    const d = new Date();
    d.setHours(h, m, s, 0);
    return d;
  });

  const submit = (d: Date) => {
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    const ss = String(d.getSeconds()).padStart(2, '0');
    onChange(`${hh}:${mm}:${ss}`);
    setVisible(false);
  };

  if (variant !== 'card') {
    return (
      <View style={styles.container}>
        <Text style={styles.label}>{label}</Text>
        <TouchableOpacity style={styles.box} onPress={() => setVisible(true)} activeOpacity={0.8}>
          <Text style={[styles.value, !value && styles.placeholder]}>{value || '選擇時間'}</Text>
          <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} />
        </TouchableOpacity>

        {visible && Platform.OS === 'android' && (
          // 安卓直接显示原生选择器
          <DateTimePicker
            value={time}
            onChange={(event, d) => {
              if (event.type === 'dismissed') {
                setVisible(false);
                return;
              }
              if (d) {
                submit(d);
              }
            }}
            mode="time"
            display="clock"
            locale="zh-TW"
          />
        )}
        {visible && Platform.OS === 'ios' && (
          // iOS使用Modal包装
          <Modal
            visible={visible}
            transparent
            animationType="fade"
            onRequestClose={() => setVisible(false)}
          >
            <View style={styles.overlay}>
              <View style={styles.sheet}>
                <DateTimePicker
                  value={time}
                  onChange={(_, d) => {
                    if (d) setTime(d);
                  }}
                  mode="time"
                  display="spinner"
                  locale="zh-TW"
                />
                <TouchableOpacity style={styles.okBtn} onPress={() => submit(time)}>
                  <Text style={styles.okText}>完成</Text>
                </TouchableOpacity>
              </View>
            </View>
          </Modal>
        )}
      </View>
    );
  }

  return (
    <View style={styles.cardContainer}>
      <View style={styles.leftRow}>
        <Text style={styles.leftLabel}>{label}</Text>
        <TouchableOpacity style={[styles.box, { flex: 1 }]} onPress={() => setVisible(true)} activeOpacity={0.8}>
          <Text style={[styles.value, !value && styles.placeholder]}>{value || '請選擇'}</Text>
          <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} />
        </TouchableOpacity>
      </View>

      {visible && Platform.OS === 'android' && (
        // 安卓直接显示原生选择器，不使用Modal
        <DateTimePicker
          value={time}
          onChange={(event, d) => {
            if (event.type === 'dismissed') {
              setVisible(false);
              return;
            }
            if (d) {
              submit(d);
            }
          }}
          mode="time"
          display="default"
          locale="zh-TW"
        />
      )}

      {visible && Platform.OS === 'ios' && (
        <Modal visible={visible} transparent animationType="slide" onRequestClose={() => setVisible(false)} presentationStyle="overFullScreen">
          <View style={styles.overlay}>
            <View style={styles.sheet}>
              <View style={styles.pickerContainer}>
                <DateTimePicker
                  value={time}
                  onChange={(_, d) => {
                    if (d) setTime(d);
                  }}
                  mode="time"
                  display="spinner"
                  textColor={Colors.black}
                  style={styles.picker}
                  locale="zh-TW"
                />
              </View>
              <TouchableOpacity style={styles.okBtn} onPress={() => submit(time)}>
                <Text style={styles.okText}>完成</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { backgroundColor: Colors.gray[100], borderRadius: 12, paddingHorizontal: 16, paddingVertical: 12 },
  cardContainer: { backgroundColor: Colors.white, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, borderWidth: 1, borderColor: Colors.gray[200] },
  label: { color: Colors.gray[400], marginBottom: 6, fontSize: 14 },
  leftRow: { flexDirection: 'row', alignItems: 'center' },
  leftLabel: { width: 88, color: Colors.gray[600], fontSize: 14 },
  box: {
    backgroundColor: Colors.white,
    borderRadius: 10,
    // 移除边框
    // borderWidth: 1,
    // borderColor: Colors.gray[200],
    paddingHorizontal: 0,
    paddingVertical: 12,
    minHeight: 44, // 确保安卓上有足够的高度
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  value: { color: Colors.black, fontSize: 16 },
  placeholder: { color: Colors.gray[400] },
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.4)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  sheet: {
    width: '90%',
    maxWidth: 400,
    backgroundColor: Colors.white,
    borderRadius: 16,
    padding: 20,
    alignSelf: 'center',
    elevation: 5, // 适中的安卓阴影层级
    shadowColor: '#000', // iOS阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  pickerContainer: {
    backgroundColor: Colors.white,
    borderRadius: 8,
    marginVertical: 8,
  },
  picker: {
    backgroundColor: Colors.white,
    color: Colors.black,
  },
  okBtn: { marginTop: 12, backgroundColor: Colors.primary, borderRadius: 12, alignItems: 'center', paddingVertical: 10 },
  okText: { color: Colors.white, fontWeight: '700' },
});

